import uvicorn
from starlette.staticfiles import StaticFiles
from starlette.responses import RedirectResponse
from fastapi.responses import HTMLResponse, FileResponse
from fastapi.templating import Jinja2Templates
from fastapi import FastAPI, Request,Form
import os
from lxml import etree
import shutil
import datetime
import csv
import pandas as pd
import json
from fastapi import FastAPI, Response
from fastapi.responses import JSONResponse
from fastapi import FastAPI, Request, Response
from starlette.responses import HTMLResponse
from fastapi import FastAPI, Form, HTTPException
from starlette.responses import RedirectResponse
from fastapi import FastAPI, Response, status
#import products

introduction='''
<h1>简单的MES系统</h1>
<h3>包含收货，领料，完工入库，发货，hold，release hold 几个步骤</h3>
<br>输入：是对方传入的ASN（xml）文件，用户点选动作，</br>
<br>输出：生成对方需要的csv格式，定时被传送回对方服务器，被剪切走，这时需要重新生成固定格式时间戳的csv文件</br>
<br>本系统工作原理：本系统无数据库，依托文件系统，对方发来的的xml文件，我们根据不同的动作，将其转移到对应动作名称的文件夹中，并把操作记录写入csv文件中</br>
<br>开发人员 </br>
<br>版本1.0</br>
'''

current_folder = os.path.dirname(os.path.abspath(__file__))

# 切换工作目录到当前文件所在的文件夹
os.chdir(current_folder)


#用户名密码数据库
fake_users_db = {
    "johndoe": "password123",
    "janedoe": "password456",

}

#在指定的文件夹中，如果没有csv文件，则生成符合格式的csv文件名字，例如554562853_341137102_XX-TRANS_1.0_20240321165100CST.csv，返回新生成的csv文件的绝对路径
#csv文件的第一行的列的名称，在col_names做好定义
#如果文件夹中有csv文件，则返回CSV文件的绝对路径
def find_csv_file(folder_path):
    # 检查文件夹是否存在
    if not os.path.isdir(folder_path):
        return "Error: Invalid directory path"

    csv_files = [f for f in os.listdir(folder_path) if f.endswith('.csv') and os.path.isfile(os.path.join(folder_path, f))]
    
    if csv_files:
        return folder_path+csv_files[0]  # 返回csv文件列表
    else:
        file_name='554562853_341137102_5W-TRANS_1.0_'+datetime.datetime.now().strftime('%Y%m%d%H%M%S')+"CST.csv"
        #print(file_name)
        name='554562853_341137102_5W-TRANS_1.0_20240321165100CST.csv'
        col_names=['MESTXID','MESTXTYPE','IFXLOTNAME','STAGESETIDENTIFIER','PRODUCTNAME',\
        'GOODWAFERQTY','GOODDIEQTY','TXREASONCODE','SHIPTOLOCATION',\
        'DATECODE','DELIVERYNUMBER','DELIVERYITEMNUMBER','IFXISBEQUALITYRISK','IFXISFEQUALITYRISK','ITEMGROUP','ITEMGOODQTY']
        with open(folder_path+file_name, 'a', newline='') as file:
            writer = csv.writer(file)
            writer.writerow(col_names)
        return folder_path+file_name


#productname的maping功能，读取csv文件，取为字典，键值key是ard的productname返回0为接收productname,1为其他productname
def read_csv_to_dict(filename):
    result_dict = {}
    with open(filename, newline='', encoding='utf-8') as csvfile:
        reader = csv.reader(csvfile)
        for row in reader:
            if row:  # 确保行不为空
                key = row[0]  # 第一列作为键
                value = (row[1], row[2])  # 第二列和第三列作为元组作为值
                result_dict[key] = value
    #print('result_dict',result_dict)
    return result_dict


#写入CSV文件,如不存在csv，则新建
def write_csv(filename,*arg):
            # 要追加的数据
    new_data=[]
    for item in arg:
        new_data.append(item)
    len_new_data=len(new_data)
    x=16-len_new_data
    for i in range(x):
        new_data.append('')
    #print('look here:',new_data)

    if os.path.exists(filename):
        print("File exists")
        # 打开CSV文件进行追加写入（如果文件不存在则创建）
        with open(filename, 'a', newline='') as file:
            writer = csv.writer(file)
            
            # 将数据写入文件
            writer.writerow(new_data)
    else:
        print("File does not exist")
                # 打开CSV文件进行追加写入（如果文件不存在则创建）
        col_names=['MESTXID','MESTXTYPE','IFXLOTNAME','STAGESETIDENTIFIER','PRODUCTNAME',\
        'GOODWAFERQTY','GOODDIEQTY','TXREASONCODE','SHIPTOLOCATION',\
        'DATECODE','DELIVERYNUMBER','DELIVERYITEMNUMBER','IFXISBEQUALITYRISK','IFXISFEQUALITYRISK','ITEMGROUP','ITEMGOODQTY']
        with open(filename, 'a', newline='') as file:
            writer = csv.writer(file)
            
            # 将数据写入文件
            writer.writerow(col_names)
        with open(filename, 'a', newline='') as file:
            writer = csv.writer(file)
            
            # 将数据写入文件
            #writer.writerow(col_names)
            writer.writerow(new_data)

#列出文件夹内的所有文件
def list_xml_files(folder_path):
    # 获取文件夹内的所有文件
    file_list = os.listdir(folder_path)
    
    # 筛选出所有的XML文件
    xml_files = [file for file in file_list if file.endswith(".xml")]
    
    return xml_files


#读取xml文件中的元素的值
def xml_item_read(file,*items):
    tree = etree.parse(file)  # 例如：XML文件名为example.xml
    root = tree.getroot()
    # 获取根元素的xmlns值
    xmlns_value = root.nsmap[None]
    ns = {"ns": xmlns_value}
    result={}
    for item in items:
        if item=='DateCode':
            result[item]= root.xpath(".//ns:lotParam[ns:lotparamName='DateCode']/ns:lotparamValue/text()", namespaces=ns)[0]
        else:
            #map products对应关系
            if item=="productName1":
                print('mapping_file',mapping_file)
                result[item]=read_csv_to_dict(mapping_file)[root.find(".//ns:{}".format('productName'), namespaces=ns).text][0]
                print('here',result[item])
                #result[item]=products.dict_product[root.find(".//ns:{}".format(item), namespaces=ns).text]
            else:
                if item=="productName2":
                    print('here1',root.find(".//ns:{}".format('productName'), namespaces=ns).text)
                    result[item]=read_csv_to_dict(mapping_file)[root.find(".//ns:{}".format('productName'), namespaces=ns).text][1]
                    print('here2',result[item])
                else:
                    result[item]=root.find(".//ns:{}".format(item), namespaces=ns).text
            print(item,result[item])
    absolute_path = file
    path, filename = os.path.split(absolute_path)
    result['filename']=filename
    return result


'''
库存表放在json文件中
在这个调整后的函数中，我们新增了一个判断，如果key为None，则返回读取出的字典data；否则返回None。这样，当调用时只提供文件名，函数会返回从文件中读取出的字典内容；而当提供了key和value时，函数只进行内容更新，不返回任何内容。

希望这个函数满足您的需要。如果您需要进一步的协助，请随时联系我。
'''
def update_nested_dict(file_path, first_level_key=None, second_level_key=None, new_value=None):
    if os.path.exists(file_path):
        with open(file_path, 'r') as file:
            data = json.load(file)
    else:
        data = {}

    if first_level_key and second_level_key and new_value:
        if first_level_key not in data:
            data[first_level_key] = {}
        data[first_level_key][second_level_key] = new_value
        with open(file_path, 'w') as file:
            json.dump(data, file)
    else:
        return data



# 创建一个 FastAPI 实例
app = FastAPI()
app.mount('/static', StaticFiles(directory='./static'), name='static')
# 指定 templates 文件夹为 HTML 模板文件目录
templates = Jinja2Templates(directory="templates")

# 首页
# User login page
@app.get("/", response_class=HTMLResponse)
async def read_item(request: Request):
    if not request.cookies.get("cookie_name"):
        return RedirectResponse('/login')
    
    print("cookie_name",request.cookies.get("cookie_name"))
##    if request.cookies.get("cookie_name")=="admin":
##        print('yes,admin')
##        return templates.TemplateResponse("admin.html", {"request": request,"context": context})
##    if request.cookies.get("cookie_name")=="cangku":
##        print('yes,cangku')
##        return templates.TemplateResponse("cangku.html", {"request": request,"context": context})
##    if request.cookies.get("cookie_name")=="shengchan":
##        print('yes,shengchan')
##        return templates.TemplateResponse("shengchan.html", {"request": request,"context": context})
##    if request.cookies.get("cookie_name")=="wuliu":
##        print('yes,wuliu')
##        return templates.TemplateResponse("wuliu.html", {"request": request,"context": context})
##    if request.cookies.get("cookie_name")=="report":
##        print('yes,report')
##        return templates.TemplateResponse("report.html", {"request": request,"context": context})
        
    #return templates.TemplateResponse("index.html", {"request": request, "context": context})
    return templates.TemplateResponse("index.html", {"request": request, "context": context})


loginhtml='''
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>
</head>
<body>
    <h2>Login</h2>
    <form action="/login" method="post">
        <label for="username">Username:</label>
        <input type="text" id="username" name="username" autocomplete="off" required>
        <label for="password">Password:</label>
        <input type="password" id="password" name="password" autocomplete="off" required>
        <button type="submit">Login</button>
    </form>
</body>
</html>
'''

##@app.get("/login1", response_class=HTMLResponse)
##async def read_item111(request: Request):
##        
##    return templates.TemplateResponse("login.html", {"request": request, "context": context})

#介绍
@app.get("/introduction", response_class=HTMLResponse)
async def introduction1(request: Request):
    if not request.cookies.get("cookie_name"):
        return RedirectResponse('/login')
    content=''
    for key in parameters.keys():
        content=content+key+':'+str(parameters[key])+'</br>'
        
        print(parameters[key])
    return     f"""
    <html>
        <head>
            <meta charset="UTF-8">
            <title>简单MES页面</title>
            {content}
        </body>
    </html>
    """
    #return HTMLResponse(content=parameters, status_code=200)

# User authentication
@app.get("/login")
async def login(request: Request):
    #cookie_value = request.cookies.get("cookie_name")
    return  HTMLResponse(content=loginhtml)
    #if username in users and users[username] == password:
    #    return templates.TemplateResponse("{}.html".format(username), {"request": request,"context": context})

    #return templates.TemplateResponse("login.html", {"request": request, "context": context})

#网页上回传的用户名密码，由下面的post路由处理，判断用户名密码正确后，跳转到set-cookie 设置客户端的cookie,加status_code=303，是为了把post的Redirect转成get
@app.post("/login")
def login_post(request: Request, username: str = Form(...), password: str = Form(...)):
    print(username,password)
    user_password = fake_users_db.get(username)
    if user_password and user_password == password:
        print('yes',username,password,'correct')
    
        #return  RedirectResponse(url='/set-cookie/{}'.format(username),status_code=303)
        return  RedirectResponse(url='/set-cookie/{}'.format(username))

#拿到用户名后，写入客户端的cookie中，完成后，跳转回首页
@app.post("/set-cookie/{name}")
def set_cookie_post(response: Response,name:str):
    print('%%%%%%%%%%%%%%%%%%')
    response.set_cookie(key="cookie_name", value=name)
    
    response.status_code = status.HTTP_301_MOVED_PERMANENTLY
    response.headers["Location"] = "/"
    return response

#检查客户端cookie的网页
@app.get("/get-cookie")
def get_cookie(request: Request):
    cookie_value = request.cookies.get("cookie_name")
    if cookie_value:
        return {"cookie_value": cookie_value}
    else:
        return {"message": "Cookie not found"}


##@app.get("/admin", response_class=HTMLResponse)
##async def read_item(request: Request):
##    return templates.TemplateResponse("index.html", {"request": request})

# 收货
@app.get("/action1",response_class=HTMLResponse)
async def action1(request: Request):
    if not request.cookies.get("cookie_name"):
        return RedirectResponse('/login')
    if request.cookies.get("cookie_name") in ['admin','cangku']:
        pass
    else:
        return "no right"
    table_data=[]
    folder_path = folder1
    for file in list_xml_files(folder_path):
        #print(xml_item_read(folder_path+file,'lotName','productName','fromStageSetName'))
        table_data.append(xml_item_read(folder_path+file,'mesLotName','productName1','goodQty1','DateCode'))
    data={"table_data":table_data}
    print('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&')
    #print(data)
    return templates.TemplateResponse("action1.html", {"request": request, "data": data,"context": context})

@app.get("/trans1")
async def trans1(request: Request, fname1:str, fname2:str, fname3:str, fname4:str,fname5:str):
    if not request.cookies.get("cookie_name"):
        return RedirectResponse('/login')
    # 指定文件和目标文件夹的路径
    print(fname1,fname2,fname3,fname4,fname5)
    folder_path = folder1
    source_file = folder_path+fname3
    destination_folder = folder2

    # 移动文件
#    logger.info('trans1',fname1,fname2,fname3)
    shutil.move(source_file, destination_folder)
    id=fname1+"_"+datetime.datetime.now().strftime("%Y%m%d%H%M%S")
    date1=datetime.datetime.now().strftime("%Y%m%d")
    csvfile=find_csv_file(csv_location)
    write_csv(csvfile,id,"ReceiveLot",fname1,"",fname2)
    write_csv(database,id,"ReceiveLot",fname1,"",fname2,"","","","","","","","","",fname4,fname5)
    update_nested_dict(jsonfile,fname1,'receive_date',date1)
    update_nested_dict(jsonfile,fname1,'status',"ReceiveLot")
    update_nested_dict(jsonfile,fname1,'goodQty1',xml_item_read(destination_folder+fname3,'goodQty1','goodQty2')['goodQty1'])
    update_nested_dict(jsonfile,fname1,'goodQty2',xml_item_read(destination_folder+fname3,'goodQty1','goodQty2')['goodQty2'])
    return RedirectResponse(url='/')

# 领料
@app.get("/action2",response_class=HTMLResponse)
async def action2(request: Request):
    if not request.cookies.get("cookie_name"):
        return RedirectResponse('/login')
    if request.cookies.get("cookie_name") in ['admin','cangku']:
        pass
    else:
        return "no right"
    table_data=[]
    folder_path = folder2
    for file in list_xml_files(folder_path):
        #print(xml_item_read(folder_path+file,'lotName','productName','fromStageSetName'))
        table_data.append(xml_item_read(folder_path+file,'mesLotName','productName','goodQty1','productName1','productName2'))
    data={"table_data":table_data}
    #print(data)
    return templates.TemplateResponse("action2.html", {"request": request, "data": data,"context": context})

@app.get("/trans2")
async def trans2(request: Request,fname1:str, fname2:str, fname3:str):
    if not request.cookies.get("cookie_name"):
        return RedirectResponse('/login')
    # 指定文件和目标文件夹的路径
    print(fname1,fname2,fname3)
    folder_path = folder2
    source_file = folder_path+fname3
    destination_folder = folder3

    # 移动文件
#    logger.info('trans2',fname1,fname2,fname3)
    shutil.move(source_file, destination_folder)
    id=fname1+"_"+datetime.datetime.now().strftime("%Y%m%d%H%M%S")
    csvfile=find_csv_file(csv_location)
    #write_csv(csvfile,id,"StageMoveLot",fname1,"WAFER-TEST",fname2)
    write_csv(csvfile,id,"StageMoveLot",fname1,"WAFER-TEST",fname2)
    #write_csv(database,id,"StageMoveLot",fname1,"WAFER-TEST",fname2)
    write_csv(database,id,"StageMoveLot",fname1,"WAFER-TEST",fname2)
    update_nested_dict(jsonfile,fname1,'status',"StageMoveLot:WAFER-TEST")
    return RedirectResponse(url='/')


# 生产入库
@app.get("/action3",response_class=HTMLResponse)
async def action3(request: Request):
    if not request.cookies.get("cookie_name"):
        return RedirectResponse('/login')
    if request.cookies.get("cookie_name") in ['admin','shengchan']:
        pass
    else:
        return "no right"
    table_data=[]
    folder_path = folder3
    for file in list_xml_files(folder_path):
        #print(xml_item_read(folder_path+file,'lotName','productName','fromStageSetName'))
        table_data.append(xml_item_read(folder_path+file,'mesLotName','productName2','goodQty1'))
    data={"table_data":table_data}
    #print(data)
    return templates.TemplateResponse("action3.html", {"request": request, "data": data,"context": context})

@app.get("/trans3")
async def trans3(request: Request, fname1:str, fname2:str, fname3:str):
    if not request.cookies.get("cookie_name"):
        return RedirectResponse('/login')
    # 指定文件和目标文件夹的路径
    print(fname1,fname2,fname3)
    folder_path = folder3
    source_file = folder_path+fname3
    destination_folder = folder4

    # 移动文件
#    logger.info('trans3',fname1,fname2,fname3)
    shutil.move(source_file, destination_folder)
    id=fname1+"_"+datetime.datetime.now().strftime("%Y%m%d%H%M%S")
    csvfile=find_csv_file(csv_location)
    #write_csv(csvfile,id,"StageMoveLot",fname1,"PROD-OUT",fname2)
    #write_csv(database,id,"StageMoveLot",fname1,"PROD-OUT",fname2)
    write_csv(csvfile,id,"StageMoveLot",fname1,"PROD-OUT",fname2)
    write_csv(database,id,"StageMoveLot",fname1,"PROD-OUT",fname2)
    update_nested_dict(jsonfile,fname1,'status',"StageMoveLot:PROD-OUT")
    return RedirectResponse(url='/')


# 发货
@app.get("/action4",response_class=HTMLResponse)
async def action4(request: Request):
    if not request.cookies.get("cookie_name"):
        return RedirectResponse('/login')
    if request.cookies.get("cookie_name") in ['admin','wuliu']:
        pass
    else:
        return "no right"
    table_data=[]
    folder_path = folder4
    for file in list_xml_files(folder_path):
        #print(xml_item_read(folder_path+file,'lotName','productName','fromStageSetName'))
        table_data.append(xml_item_read(folder_path+file,'mesLotName','productName2','goodQty1','goodQty2'))
    data={"table_data":table_data}
    print(data)
    return templates.TemplateResponse("action4.html", {"request": request, "data": data,"context": context})

@app.get("/trans4")
#async def trans4(fname1:str, fname2:str, fname3:str,fname4:int,fname5:int,fname6:str,fname7:str,fname8:str):
async def trans4(request: Request, fname1:str, fname2:str, fname3:str,fname4:int,fname5:int,fname6:str,fname7:str):
    if not request.cookies.get("cookie_name"):
        return RedirectResponse('/login')
    # 指定文件和目标文件夹的路径
    print(fname1,fname2,fname3)
    folder_path = folder4
    source_file = folder_path+fname3
    destination_folder = folder5

    # 移动文件
#    logger.info('trans4',fname1,fname2,fname3,fname4,fname5,fname6,fname7,fname8)
    shutil.move(source_file, destination_folder)
    id=fname1+"_"+datetime.datetime.now().strftime("%Y%m%d%H%M%S")
    csvfile=find_csv_file(csv_location)
    #write_csv(csvfile,id,"ShipLot",fname1,"",fname2,fname4,fname5,"",fname6,fname7)
    write_csv(csvfile,id,"ShipLot",fname1,"",fname2,fname4,fname5,"",fname6,fname7)
    #write_csv(database,id,"ShipLot",fname1,"",fname2,fname4,fname5,"",fname6,fname7)
    write_csv(database,id,"ShipLot",fname1,"",fname2,fname4,fname5,"",fname6,fname7)
    update_nested_dict(jsonfile,fname1,'status',"ShipLot")
    return RedirectResponse(url='/')


#hold
@app.get("/hold")
async def hold(request: Request, fname1:str, fname2:str, fname3:str,q:str):
    if not request.cookies.get("cookie_name"):
        return RedirectResponse('/login')
    # 指定文件和目标文件夹的路径
    print(fname1,fname2,fname3)
    source={}
    source['1']=folder1
    source['2']=folder2
    source['3']=folder3
    source['4']=folder4
    source['5']=folder5
    source['6']=folder6
    folder_path = source[q]
    source_file = folder_path+fname3
    destination_folder = source['6']

    # 移动文件
#    logger.info('hold',fname1,fname2,fname3,q)
    shutil.move(source_file, destination_folder)
    os.rename(destination_folder+fname3,destination_folder+q+'_'+fname3)
    id=fname1+"_"+datetime.datetime.now().strftime("%Y%m%d%H%M%S")
    csvfile=find_csv_file(csv_location)
    #write_csv(csvfile,id,"HoldLot",fname1,"",fname2,"","","HOLD")
    print('we are holding now',id,"HoldLot",fname1,"",fname2,"","","HOLD")
    write_csv(csvfile,id,"HoldLot",fname1,"",fname2,"","","HOLD")
    #write_csv(database,id,"HoldLot",fname1,"",fname2,"","","HOLD")
    write_csv(database,id,"HoldLot",fname1,"",fname2,"","","HOLD")
    update_nested_dict(jsonfile,fname1,'status',"hold")
    return RedirectResponse(url='/')


#release hold
@app.get("/releasehold",response_class=HTMLResponse)
async def releasehold(request: Request):
    if not request.cookies.get("cookie_name"):
        return RedirectResponse('/login')

    table_data=[]
    folder_path = folder6
    for file in list_xml_files(folder_path):
        #print(xml_item_read(folder_path+file,'lotName','productName','fromStageSetName'))
        table_data.append(xml_item_read(folder_path+file,'mesLotName','productName2','goodQty1'))
    data={"table_data":table_data}
    #print(data)
    return templates.TemplateResponse("action5.html", {"request": request, "data": data,"context": context})

@app.get("/trans5")
async def trans5(request: Request, fname1:str, fname2:str, fname3:str):
    if not request.cookies.get("cookie_name"):
        return RedirectResponse('/login')
    # 指定文件和目标文件夹的路径
    print(fname1,fname2,fname3)
    print('000000000000000000')
    source={}
    source['1']=folder1
    source['2']=folder2
    source['3']=folder3
    source['4']=folder4
    source['5']=folder5
    source['6']=folder6
    print('**********************')
    print(folder6+fname3,folder6+fname3[2:])
    os.rename(folder6+fname3,folder6+fname3[2:])
#    logger.info('release',fname1,fname2,fname3)
    shutil.move(folder6+fname3[2:],source[fname3[0]])

    id=fname1+"_"+datetime.datetime.now().strftime("%Y%m%d%H%M%S")
    csvfile=find_csv_file(csv_location)
    #write_csv(csvfile,id,"ReleaseLot",fname1,"",fname2,"","","HOLD")
    write_csv(csvfile,id,"ReleaseLot",fname1,"",fname2,"","","HOLD")
    #write_csv(database,id,"ReleaseLot",fname1,"",fname2,"","","HOLD")
    write_csv(database,id,"ReleaseLot",fname1,"",fname2,"","","HOLD")
    update_nested_dict(jsonfile,fname1,'status',"releasehold")
    return RedirectResponse(url='/')


@app.get("/dir")
def read_root(request: Request):
    if not request.cookies.get("cookie_name"):
        return RedirectResponse('/login')
    #return {"Hello": "World"}
    return RedirectResponse(url='/files/1?q=')


@app.get("/files/{item_id}")
def read_files(request:Request, item_id: str, q: str = None):
    if not request.cookies.get("cookie_name"):
        return RedirectResponse('/login')
    
    #return {"item_id": item_id, "q": q}
    data=['hello','china']
    print('q before:')
    q0=location+'/'+q
    print('q0 after:',q0)
    if os.path.isdir(q0):
        list0=os.listdir(q0)
        print('*****************folder************************'+q0)
    #return x
        return templates.TemplateResponse("dir.html", {"request": request, "id": list0, "id1":"xxxx", "q":q})
    else:
        print('&&&&&&&&&&&file&&&&&&&&&&&&&&&&&&&&&&'+q0)
        q=q.replace(' ','%20')
        print('q again:::::::',q)
        return RedirectResponse(url='/static'+q)

@app.get("/pd", response_class=HTMLResponse)
async def read_csv_file(request:Request, q=str):
    if not request.cookies.get("cookie_name"):
        return RedirectResponse('/login')
    # 读取CSV文件并转换为HTML表格
    print('q',q)
    report={}
    report['0']=database
    df = pd.read_csv(report[q])
    df = df.sort_index(ascending=False)
    html_table = df.to_html(index=False,na_rep='',float_format='%.0f')
    
    # 返回HTML响应
    return f"""
    <html>
        <head>
            <title>CSV Viewer222</title>
        </head>
        
        <body>
        <a href="/static/report/database/database.csv">CSV总表</a>
            {html_table}
        </body>
    </html>
    """



### 用户登录提交
##@app.post("/login")
##async def login(username: str = Form(...), password: str = Form(...)):
##    if username in users and users[username] == password:
##        return {"message": "Login successful", "username": username}
##    else:
##        return {"message": "Invalid username or password"}

# 需要登录后的操作，记录用户是谁
##@app.post("/loggedin_operation")
##async def loggedin_operation(username: str = Form(...)):
##    # 执行需要记录用户的操作
##    return {"message": "Operation recorded for user", "username": username}

def get_directory_structure(base_path):
    result = ""
    for item in os.listdir(base_path):
        item_path = os.path.join(base_path, item)
        if os.path.isfile(item_path):
            result += f'<a href="/download?file={item_path}">{item}</a><br>'
        elif os.path.isdir(item_path):
            result += f'<p>{item}</p>{get_directory_structure(item_path)}'
    return result

@app.get("/dir2", response_class=HTMLResponse)
async def show_directory_structure(request:Request):
    if not request.cookies.get("cookie_name"):
        return RedirectResponse('/login')
    structure = get_directory_structure(csv_location)
    print('structure',structure)
    return f"""
    <!DOCTYPE html>
    <html>
    <head>
        <title>Static Directory Listing</title>
    </head>
    <body>
    
    {structure}
    </body>
    </html>
    """

@app.get("/download")
async def download_file(request:Request, file: str):
    if not request.cookies.get("cookie_name"):
        return RedirectResponse('/login')
    return FileResponse(file, filename=os.path.basename(file))


# 创建一个展示字典内容的接口
@app.get("/display_dict", response_class=HTMLResponse)
async def display_nested_dict_content(request: Request):
    if not request.cookies.get("cookie_name"):
        return RedirectResponse('/login')
    data=update_nested_dict(jsonfile)
    data1={}
    for key in data.keys():
        if data[key]['status']!="ShipLot":
            data1[key]=data[key]
    return templates.TemplateResponse("display_dict.html", {"request": request, "data": data1})


# 运行应用
if __name__ == "__main__":
    parameters={}
    parameters['introduction']=introduction
    parameters['status']='生产production'
    
    parameters['current_folder']=current_folder
    parameters['mode']={'value':True,'comments':'True为不循环，正式，False为循环，发货后进入待处理文件夹'}
    parameters['folder1']={'location':"1.待处理\\",'comments':'ASN的xml文件进入的第1个文件夹，也就是待收货的文件夹'}
    parameters['folder2']={'location':"2.已接收\\",'comments':'ASN的xml文件进入的第2个文件夹，也就是收货以后，待领料，已接收的文件夹'}
    parameters['folder3']={'location':"3.已领料\\",'comments':'ASN的xml文件进入的第3个文件夹，也就是收货以后，待生产，已领料的文件夹'}
    parameters['folder4']={'location':"4.已入库\\",'comments':'ASN的xml文件进入的第4个文件夹，也就是收货以后，待发货，已生产的文件夹'}
    if parameters['mode']['value']:
        parameters['folder5']={'location':"5.已发运\\",'comments':'ASN的xml文件进入的第5个文件夹，也就是发货以后的最终的文件夹'}
    else:
        parameters['folder5']=parameters['folder1']
    parameters['folder6']={'location':"6.hold\\",'comments':'ASN的xml文件进入的第6个文件夹，也就是hold住的文件夹'}
    parameters['csv_location']={'location':"..\\output\\",'comments':'csv文件夹，也就是要被定时剪切走，传回给对面的文件夹，被剪切走后就是空的'}
    parameters['database']={'location':"static\\report\\database\\database.csv",'comments':'总表，记录所有的动作的历史记录'}
    parameters['jsonfile']={'location':"static\\report\\database\\json.json",'comments':'库存表，记录所有库存'}
    parameters['mapping']={'location':"static\\report\\database\\productname.csv",'comments':'mapping表，记录所有mapping'}
    parameters['port']=88
    
    folder1=parameters['folder1']['location']    
    folder2=parameters['folder2']['location']
    folder3=parameters['folder3']['location']
    folder4=parameters['folder4']['location']
    folder5=parameters['folder5']['location']
    folder6=parameters['folder6']['location']
    csv_location=parameters['csv_location']['location']
    database=parameters['database']['location']
    jsonfile=parameters['jsonfile']['location']
    mapping_file=parameters['mapping']['location']
    #context = {"request": request, "my_var": parameters['status']}
    context = {"my_var": parameters['status']}
    location='static'


    uvicorn.run(app, host="0.0.0.0", port=parameters['port'])
